import {imgFilter} from './filter'
/**
 * 保存图片
 * @param {string} Url 需要保存的文件
 */
export var saveImage = (Url) => {
	// #ifndef H5
	uni.saveImageToPhotosAlbum({
		filePath: Url,
		success: () => {
			uni.showToast({
				title: '保存成功'
			})
		}
	})
	// #endif
	// #ifdef H5
	var triggerEvent = "touchstart"; //指定下载方式
	var blob = new Blob([''], {
		type: 'application/octet-stream'
	}); //二进制大型对象blob
	var url = URL.createObjectURL(blob); //创建一个字符串路径空位
	var a = document.createElement('a'); //创建一个 a 标签
	a.href = Url; //把路径赋到a标签的href上
	//正则表达式，这里是把图片文件名分离出来。拿到文件名赋到a.download,作为文件名来使用文本
	a.download = Url.replace(/(.*\/)*([^.]+.*)/ig, "$2").split("?")[0];
	/* var e = document.createEvent('MouseEvents');  //创建事件（MouseEvents鼠标事件）
	e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); //初始化鼠标事件（initMouseEvent已弃用）*/

	//代替方法。创建鼠标事件并初始化（后面这些参数我也不清楚，参考文档吧 https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent）
	var e = new MouseEvent('click', (true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null));
	//派遣后，它将不再执行任何操作。执行保存到本地
	a.dispatchEvent(e);
	//释放一个已经存在的路径（有创建createObjectURL就要释放revokeObjectURL）
	URL.revokeObjectURL(url);
	// #endif
}
export let imgPreview = (urlss, current) => {
	let urls = null
	if (Array.isArray(urlss)) {
		urls = urlss.map(v => imgFilter(v))
	} else {
		urls = [imgFilter(urlss)]
	}
	uni.previewImage({
		current,
		urls
	});
}
/**
 * 图片压缩
 * @param {string} src 文件路径
 * @param {string} fileSize 规定多少m需要压缩
 * @param {string} size 压缩的质量
 * @param {string} type 压缩后返回的文件类型
 */
export let compressImage = (src, fileSize, size = 30, type) => {
	return new Promise((result, err) => {
		if (fileSize / 1024 / 1024 < 1) return result(src)
		//除了H5
		// #ifndef H5 
		uni.compressImage({
			src,
			quality: size,
			success({
				tempFilePath
			}) {
				result(tempFilePath)
			}
		})
		// #endif
		//只有H5
		// #ifdef H5
		var img = new Image();
		img.src = src;
		img.onload = function() {
			var that = this;
			var h = that.height; // 默认按比例压缩
			var w = that.width;
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			var width = document.createAttribute("width");
			width.nodeValue = w;
			var height = document.createAttribute("height");
			height.nodeValue = h;
			canvas.setAttributeNode(width);
			canvas.setAttributeNode(height);
			ctx.drawImage(that, 0, 0, w, h);
			var base64 = canvas.toDataURL('image/' + src.split('.').pop(), size); //压缩比例
			canvas = null;
			if (type == 'base64') {
				result(base64);
			} else {
				var blob = base64ToBlob(base64);
				var blobUrl = window.URL.createObjectURL(blob); //blob地址
				result(blobUrl);
			}
		}
		// #endif
	})

}
/**
 * 上传文件
 * @param {string} v 文件路径
 * @param {string} size 文件大小
 */
export let uploadFile = (api='/Files/UploadImage', v, size) => {
	uni.showToast({
		title: '上传中...'
	})
	return new Promise(async (ress, err) => {
		let result = await compressImage(v, size)
		uni.uploadFile({
			url: uni.$config.baseUrl + api,
			filePath: result,
			name: 'file',
			success(res) {
				const data = JSON.parse(res.data);
				let url = data.result.webUrl;
				ress(url)
			},
			fail(error) {
				err(error)
				console.log(error, 'error');
			},
			complete() {
				uni.hideToast();
			}
		});
	})
}
